from collections import OrderedDict

from apps.goods.models import GoodsChannel


def get_categories():
    # 查询出所有商品频道数据  并按频道组名和组内顺序排序
    channels = GoodsChannel.objects.order_by('group_id', 'sequence')

    # 生成一个自动排序的字典
    categories = OrderedDict()
    # 遍历数据
    for channel in channels:
        # 提取出group_id
        group_id = channel.group_id
        # 如果group_id不存在字典内
        if group_id not in categories:
            # 就存入字典key为group_id 值为 一个字典  字典内两个列表  一个频道一个子级频道
            categories[group_id] = {
                'channels': [],
                'sub_cats': []
            }

        # 查询一级频道内的所有商品类别
        category1 = channel.category

        # 把一级频道的数据放到列表内
        categories[group_id]['channels'].append({
            'id': category1.id,
            'name': category1.name,
            'url': channel.url
        })

        # 查询子级频道
        category2s = category1.subs.all()
        # 遍历子级频道数据存入列表
        for cat2 in category2s:
            # 遍历子级频道
            category3s = cat2.subs.all()
            sub_cats3 = []
            # 数据存入列表
            for cat3 in category3s:
                sub_cats3.append({
                    'id': cat3.id,
                    'name': cat3.name
                })

            categories[group_id]['sub_cats'].append({
                'id': cat2.id,
                'name': cat2.name,
                'sub_cats': sub_cats3
            })
    # 返回数据
    return categories


def get_breadcrumb(category):
    """
    获取面包屑导航
    :param category: 商品类别
    :return: 面包屑导航字典
    """
    breadcrumb = {
        'cat1': '',
        'cat2': '',
        'cat3': '',
    }
    if category.parent is None:
        # 当前类别为一级类别
        breadcrumb['cat1'] = category.name
    elif category.parent.parent is None:
        # 当前类别为三级
        breadcrumb['cat2'] = category.name
        breadcrumb['cat1'] = category.parent.name

    else:
        # 当前类别为二级
        breadcrumb['cat3'] = category.name
        breadcrumb['cat2'] = category.parent.name
        breadcrumb['cat1'] = category.parent.parent.name

    return breadcrumb


"""
规格选项
"""


def get_goods_specs(sku):
    # 构建当前商品的规格键
    sku_specs = sku.specs.order_by('spec_id')
    sku_key = []
    for spec in sku_specs:
        sku_key.append(spec.option.id)

    # 获取当前商品的所有SKU
    skus = sku.spu.sku_set.all()
    # 构建不同规格参数（选项）的sku字典
    spec_sku_map = {}
    for s in skus:
        # 获取sku的规格参数
        s_specs = s.specs.order_by('spec_id')
        # 用于形成规格参数-sku字典的键
        key = []
        for spec in s_specs:
            key.append(spec.option.id)
        # 向规格参数-sku字典添加记录
        spec_sku_map[tuple(key)] = s.id

    # 以下代码为：在每个选项上绑定对应的sku_id值
    # 获取当前商品的规格信息
    goods_specs = sku.spu.specs.order_by('id')
    # 若当前sku的规格信息不完整，则不再继续
    if len(sku_key) < len(goods_specs):
        return
    for index, spec in enumerate(goods_specs):
        # 复制当前sku的规格键
        key = sku_key[:]
        # 该规格的选项
        spec_options = spec.options.all()
        for option in spec_options:
            # 在规格参数sku字典中查找符合当前规格的sku
            key[index] = option.id
            option.sku_id = spec_sku_map.get(tuple(key))
        spec.spec_options = spec_options

    return goods_specs
